package org.example.communication_room.service;

import org.example.communication_room.Controller.UserController;
import org.example.communication_room.dao.Friendship;
import org.example.communication_room.dao.User;
import org.example.communication_room.repository.FriendshipRepository;
import org.example.communication_room.repository.UserRepository;
import org.example.communication_room.service.interfaces.FriendShipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FriendshipServiceImpl implements FriendShipService {

    @Autowired
    private FriendshipRepository friendshipRepository;

    @Autowired
    private UserRepository userRepository;
    // 日志初始化
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    // 添加好友
    public Friendship addFriend(Long requesterId, Long receiverId) {
        User requester = userRepository.findById(requesterId).orElseThrow();
        User receiver = userRepository.findById(receiverId).orElseThrow();
        // 检查是否已存在同样的好友请求
        if (friendshipRepository.existsByRequesterAndReceiver(requester, receiver)) {
            throw new IllegalArgumentException("已经添加过该好友，请勿重复添加");
        }

        Friendship friendship = new Friendship();
        friendship.setRequester(requester);
        friendship.setReceiver(receiver);
        friendship.setStatus("pending");
        return friendshipRepository.save(friendship);
    }
    // 接收好友请求
    public void acceptFriendRequest(Long requesterId, Long receiverId) {
        logger.info("Receiver ID: {}, Requester ID: {}", receiverId, requesterId);

        // 获取接收方和请求方的用户对象
        User receiver = userRepository.findById(receiverId)
                .orElseThrow(() -> new IllegalArgumentException("Receiver not found with ID: " + receiverId));
        User requester = userRepository.findById(requesterId)
                .orElseThrow(() -> new IllegalArgumentException("Requester not found with ID: " + requesterId));
        // 获取FriendShip对象
        Optional<Friendship> optionalFriendship = Optional.ofNullable(friendshipRepository.findByReceiverAndRequester(receiver, requester));
        if (!optionalFriendship.isPresent()) {
            throw new RuntimeException("在给定用户之间找不到好友请求.");
        }

        Friendship friendship = optionalFriendship.get();
        logger.info("Found friendship: {}", friendship);
        if ("accepted".equals(friendship.getStatus())) {
            logger.info("已接受从{}到{}的好友请求。未采取任何行动", requesterId, receiverId);
            throw new IllegalArgumentException("好友请求已经接受");
        }
        // 确认当前用户(接收方)为指定接收方
        if (!friendship.getReceiver().getUserId().equals(receiverId)) {
            throw new IllegalArgumentException("只有指定的接收者才能接受此好友请求。");
        }

        // 更新状态
        friendship.setStatus("accepted");
        friendshipRepository.save(friendship);
        logger.info("Friend request from {} to {} has been accepted.", requesterId, receiverId);
    }



    public void deleteFriend(Long receiverId, Long requesterId) {
        logger.info("receiver"+receiverId+"receiver"+requesterId);

        User receiver = userRepository.findById(receiverId)
                .orElseThrow(() -> new IllegalArgumentException("Receiver not found with ID: " + receiverId));
        User requester = userRepository.findById(requesterId)
                .orElseThrow(() -> new IllegalArgumentException("Requester not found with ID: " + requesterId));
        logger.info("receiver"+receiver.getUsername()+"receiver"+requester.getUsername());
        Friendship friendship = friendshipRepository.findByReceiverAndRequester(receiver, requester);
        logger.info(friendship.getStatus()+"");
        if (friendship == null) {
            throw new IllegalArgumentException("找不到指定好友.");
        }
        if (!"accepted".equals(friendship.getStatus())) {
            throw new IllegalArgumentException("找不到指定好友");
        }

        friendshipRepository.deleteById(friendship.getId());
        logger.info(receiver.getUsername()+"已经被删除");
    }

    //    搜索
    public List<Map<String, Object>> searchUsersWithFriendshipStatus(String query, Long requesterId) {
        List<User> users = userRepository.findByUsernameContainingAndUserIdNot(query, requesterId);
        List<Map<String, Object>> result = new ArrayList<>();
        for (User user : users) {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("username", user.getUsername());

            String status = "none";
            User requester = userRepository.findById(requesterId).orElse(null);
            Friendship friendship = friendshipRepository.findByRequesterAndReceiver(requester, user);
            if (friendship == null) {
                friendship = friendshipRepository.findByRequesterAndReceiver(user, requester);
            }
            if (friendship != null) {
                status = friendship.getStatus();
            }
            userInfo.put("status", status);
            result.add(userInfo);
        }
        return result;
    }


    // 获取用户收到的待处理好友请求
    public List<Friendship> findPendingFriendRequests(Long userId) {
        User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found"));
        return friendshipRepository.findAllByRequesterAndStatus(user, "pending");
    }
    public List<Map<String, Object>> findAcceptedFriends(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("Receiver not found with ID: " + userId));
        List<Friendship> friendships = friendshipRepository.findAllByRequesterAndStatus(user, "accepted");
        return friendships.stream()
                .map(friendship -> {
                    Map<String, Object> friendData = new HashMap<>();
                    User friend = friendship.getRequester();  // Assuming the requester is the friend in this relationship

                    // Check if the current user is the requester, then the friend would be the receiver
                    if (friendship.getRequester().getUserId().equals(userId)) {
                        friend = friendship.getReceiver();
                    }

                    friendData.put("userId", friend.getUserId());
                    friendData.put("username", friend.getUsername());
                    return friendData;
                })
                .collect(Collectors.toList());
    }

}
